#include <stdio.h>
#include <stdlib.h>

#define COUNT 1024

int search(int min, int max);

int cost = 0;
int num[COUNT];
int find = 0;

int main (int argc, char *argv[]) {
	// fill in the array with numbers from 1~100
	for (int i=1 ; i<=COUNT; i++) {
		num[i] = i;
	}

	// get number to find
	if (argc == 2) {
		find = atoi(argv[1]);
	} else {
		find = 26;
	}

	// initial boundry
	int min = 0;
	int max = COUNT;

	printf("初始边界: min=%d, max=%d\n", min, max);

	int found = search(min, max);

	if (found) {
		printf("It took %d times to find %d!\n", cost, find);
	} else {
		printf("Oops, not found!\n");
	}

}

int search(int min, int max) {
	cost++;
	
	// return 0 two boundry overlaps
	if (min > max) {
		return 0;
	}

	int i = min + (max - min) / 2;

	if (num[i] == find) {
		return num[i];
	} else {
		if (num[i] > find) {
			max = i;
			printf("向下找: min=%d, max=%d\n", min, max);
			return search(min, max);
		} else {
			if (i%2 == 1) {
				i = i + 1;	
			}
			min = i;
			printf("向上找: min=%d, max=%d\n", min, max);
			return search(min, max);
		}
	}

}

